<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: liguohua@clcw.com.cn  Blog:http://blog.sina.com.cn/saverneo        |
// +------------------------------------------------------------------------+
//

/**车辆维修保养记录报告**/
namespace AuctionAppApi\Service;

use AuctionCore\CarResource\DealerRepairLog;
use AuctionCore\CarResource\ThirdRepairLog;
use AuctionCore\Common\PhpRedis;
use AuctionCore\System\SystemConf;
use Common\Lib\Chaboshi\CBS;
use Common\Lib\Chejianding\CJD;
use AuctionCore\CarResource\CarRepairInfo;
use AuctionCore\System\AuctionException;

class RepairService
{
	protected $uid = '';
	protected $user_name = '';

	protected $redis_report_key = null;
	protected $redis_rand_key = null;

	protected $cbs_callback_url = 'http://appapi.lpaiche.com/Repair/NotifyCbs';

	public function __construct() {
		//使用redis缓存查询数据
		$this->redis = new PhpRedis();
		$this->redis_report_key = getRedisKeyByCode('REDIS_KEY','100014');
		$this->redis_rand_key = getRedisKeyByCode('REDIS_KEY','100015');
		$this->options = SystemConf::getConfByName('SEARCH_OPTIONS');
	}


	/**
	 * @param $vin
	 * @param int $log_id
	 * @return array|bool
	 * @throws AuctionException
	 */
	public function get_report($vin,$log_id=0){
		$repair = new CarRepairInfo();
		$repair_log = new DealerRepairLog();
		//检测其他平台是否已查询过该车辆

		//获取报告ID
		$is_had = $this->redis->hget($this->redis_report_key,$vin);
		//检测redis是否查询过车辆信息
		if($is_had){
			$repair = new CarRepairInfo();
			$repair_info = $repair->get_repair_info($is_had);
			$this->update_third($vin,$repair_info['third_party'],$repair_info['rid']);
			return $repair_info;
		}else{
			$is_set = $repair->get_repair_info($vin);
			if($is_set){
				$this->redis->hset($this->redis_report_key,$vin,$is_set['rid']);
				$this->update_third($vin,$is_set['third_party'],$is_set['rid']);
				return $is_set;
			}
			//第三方查询顺序判断
			if($this->options['value'] == 1){
				//状态为1时  先查询查博士，查询失败后查询车鉴定
				$repair_log->update_by_id($log_id,array('type'=>1));
				$cbs_state = $this->cbs_search($vin,$this->cbs_callback_url);
				if($cbs_state && is_array($cbs_state)){
					return $cbs_state;
				}elseif($cbs_state==1102){
					return array('code'=>302,'msg'=>"数据生成中，请稍后再试");
				}
				$repair_log->update_by_id($log_id,array('type'=>2));
				$cjd_state = $this->cjd_search($vin);
				if($cjd_state & is_array($cjd_state)){
					return $cjd_state;
				}elseif($cjd_state==1102){
					return array('code'=>302,'msg'=>"数据生成中，请稍后再试");
				}
			}else{
				//状态不为1时  先查询车鉴定，查询失败后查询查博士
				$repair_log->update_by_id($log_id,array('type'=>2));
				$cjd_state = $this->cjd_search($vin);
				if($cjd_state & is_array($cjd_state)){
					return $cjd_state;
				}elseif($cjd_state==1102){
					return array('code'=>302,'msg'=>"数据生成中，请稍后再试");
				}
				$repair_log->update_by_id($log_id,array('type'=>1));
				$cbs_state = $this->cbs_search($vin,$this->cbs_callback_url);
				if($cbs_state && is_array($cbs_state)){
					return $cbs_state;
				}elseif($cbs_state==1102){
					return array('code'=>302,'msg'=>"数据生成中，请稍后再试");
				}
			}
			return array('code'=>500,'msg'=>"查询不到车辆信息");
		}
	}

	/**状态修改
	 * @param $vin
	 * @param $type
	 */
	public  function  update_third($vin,$type,$rid=0){
		$third_log  = new ThirdRepairLog();
		$status   = $third_log->get_log_by_type(array('vin'=>$vin,'type'=>$type,'source'=>2));
		if($status&&($status['search_state']!=2) ){
			$third_log->update_by_id(array('search_state'=>2),array('id'=>$status['id']));
		}
	}

	/**第三方查询记录方法
	 * @param $data
	 * @return bool
	 */
	public function third_choic($data){
		$third_log  = new ThirdRepairLog();
		$search_data = array(
				'type'=>$data['type'],
				'vin'=>$data['vin'],
				'source'=>$data['source']
		);
		$status = $third_log->get_log_by_type($search_data);
		if($status){
			switch($status['search_state']){
				case 3:
					if($data['search_state']==2){
						$option= array('search_state'=>2);
						$third_log->update_by_id($option,array('id'=>$status['id']));
					}elseif($data['search_state']==1){
						$option= array('search_state'=>1);
						$third_log->update_by_id($option,array('id'=>$status['id']));
						break;
					}
					break;
				case 1:
					if($data['search_state']==2){
						$option= array('search_state'=>2);
						$third_log->update_by_id($option,array('id'=>$status['id']));
					}elseif($data['search_state']==3){
						$option= array('search_state'=>3);
						$third_log->update_by_id($option,array('id'=>$status['id']));
					}
					break;
				case 2:
					return true;
					break;
			}
		}else{
			$third_log->save_log($data);
		}

	}


	/**
	 * 查博士查询
	 * @param $vin
	 * @return bool
	 * @throws AuctionException
	 */
	public function cbs_search($vin,$callback=''){
		if(empty($callback)){
			$callback = $this->cbs_callback_url;
		}
		//实例化查博士查询
		$cbs = CBS::getInstance();
		//判断该vin码是否支持查询
		$is_search = $cbs->getCheckBrand($vin);
		$is_search = json_decode($is_search,true);
		info_log('repair_step',array('cbs_user_status_check_vin'=>$is_search));
		$option = array(
				'vin'=>$vin,
				'type'=>1,
				'source'=>2,
				'createtime'=>date('Y-m-d H:i:s')
		);
		if($is_search['Code']==1106){
			$this->redis->set($this->redis_rand_key,0);
			$vin_cbs = getRedisKeyByCode('REDIS_KEY','100016');
			$order_id = $this->redis->hget($vin_cbs,$vin);
			if(!$order_id) {
				//购买报告
				$order_msg = $cbs->getBuyReport($vin, null, null,$callback);
				$order_msg = json_decode($order_msg);
				if($order_msg->Code==0){
					$order_id = $order_msg->orderId;
					$this->redis->hset($vin_cbs, $vin, $order_id);
				}else{
					$option['search_state'] = 3;
					$this->third_choic($option);
					return false;
				}
			}
			//获取报告Json数据
			$car_report_jsondata = $cbs->getNewReportJson($order_id);
			info_log('repair_step',array('cbs_report_jsondata_getjsondata'=>$car_report_jsondata));
			$car_report_jsondata = json_decode($car_report_jsondata,true);
			if(is_array($car_report_jsondata)){
				$option['order_id']= $order_id;
				switch($car_report_jsondata['Code']){
					case 1102:
						$option['search_state'] = 1;
						$this->third_choic($option);
						return $car_report_jsondata['Code'];
						break;
					case 1104:
						//入库并返回格式
						$option['search_state'] = 2;
						$result = $this->public_data($vin,$car_report_jsondata,1,$order_id);
						if(isset($result['rid'])){
							$option['rid'] = $result['rid'];
						}else{
							$option['search_state'] = 3;
						}
						$this->third_choic($option);
						return $result;
						break;
					default:
						$option['search_state'] = 3;
						$this->third_choic($option);
						return false;
						break;
				}
			}
			$option['search_state'] = 3;
			$this->third_choic($option);
			return false;
		}
		$option['search_state'] = 3;
		$this->third_choic($option);
		return false;
	}

	/**
	 * 车鉴定
	 * @param $vin
	 * @return bool
	 */
	public function cjd_search($vin){
		$cjd = new CJD();
		//检测车鉴定账号状态
		$user = $cjd->accountInfo('check_user');
		info_log('repair_step',array('cjd_user_status_check_user'=>$user));
		$option = array(
				'vin'=>$vin,
				'type'=>2,
				'source'=>2,
				'createtime'=>date('Y-m-d H:i:s')
		);
		//如果剩余次数小于1   则返回 使用查博士
		if($user['info']['status']==1 && $user['info']['balance']>1){
			$vin_cjd = getRedisKeyByCode('REDIS_KEY','100017');
			$order_id = $this->redis->hget($vin_cjd,$vin);
			$this->redis->set($this->redis_rand_key,1);
			if(!$order_id){
				$order = $cjd->accountInfo('buy_report',array('vin'=>$vin));
				info_log('repair_step',array('cjd_order_status_get_order'=>$order));
				if($order['info']['status']==1){
					$order_id = $order['info']['orderId'];
					$this->redis->hset($vin_cjd, $vin, $order_id);
				}elseif($order['info']['status']==11){
					return 1102;
				}else{
					$option['search_state'] = 3;
					$this->third_choic($option);
					return false;
				}
			}
			//查询入库
			$result = $this->cjd_inser_repair($vin,$order_id);
			return $result;
		}else{
			$option['search_state'] = 3;
			$this->third_choic($option);
			return false;
		}

	}

	/**车鉴定查询入库方法
	 * @param $order_id
	 * @return array|bool
	 */
	public function  cjd_inser_repair($vin,$order_id){
		$cjd = new CJD();
		$option = array(
				'vin'=>$vin,
				'order_id'=>$order_id,
				'type'=>2,
				'source'=>2,
				'createtime'=>date('Y-m-d H:i:s')
		);
		//查看报告状态
		$order_status = $cjd->accountInfo('get_order_info',array('order_id'=>$order_id));
		info_log('repair_step',array('cjd_order_status_get_order_status'=>$order_status));
		if($order_status['info']['status']==1 && $order_status['info']['orderStatus']==2){
			//获取报告Json数据
			$order_info =$cjd->accountInfo('report_data_2',array('order_id'=>$order_id));
			if($order_info['info']['status']==5){
				foreach($order_info['reportJson'] as $key=>$val){
					$order_info['reportJson'][$key]['date'] = $val['repairDate'];
					unset($order_info['reportJson'][$key]['repairDate']);
				}
				$order_info['normalRepairRecords'] = $order_info['reportJson'];
				unset($order_info['reportJson']);
				$num = count($order_info['normalRepairRecords']);
				$order_info['basic']['lastMainTainTime'] = $order_info['basic']['lastRepairTime'] = $order_info['normalRepairRecords'][$num-1]['date'];
				$result = $this->public_data($vin,$order_info,2,$order_id);
				if(isset($result['rid'])){
					$option['rid'] = $result['rid'];
				}
				$this->third_choic($option);
				return $result;
			}
			$option['search_state'] = 3;
			$this->third_choic($option);
			return false;
		}elseif($order_status['info']['status']==1 && $order_status['info']['orderStatus']==3){
			info_log('repair_step',array('cjd_order_status_get_order_status_searching'=>$order_status));
			$option['search_state'] = 1;
			$this->third_choic($option);
			return   1102;
		}
		$option['search_state'] = 3;
		$this->third_choic($option);
		return false;
	}



	/**
	 * @param $result   数据返回结果
	 * @param $type     1 查博士   2 车鉴定
	 */
	private  function public_data($vin,$result,$type,$order_id=''){
		$insert_data = array(
				'vin' => $vin,
				'third_party'=>$type,
				'createtime' => date('Y-m-d H:i:s'),
				'componentanalyzerepairtimes'=>'',
				'outsideanalyzerepair'=>'',
				'constructanalyzerepairrecords'=>'',
				'lastmaintaintime'=>'',
				'lastrepairtime'=>'',
				'maintaintimes'=>'',
				'mileageeveryyear'=>'',
				'order_id'=>$order_id,
				'type'=>2
		);
		$orther_data = array(
				'transmissiontype'=>'',
				'manufacturer'=>'',
				'makedate'=>'',
				'cartype'=>'',
				'displacement'=>'',
				'productionarea'=>'',
				'effluentstandard'=>'',
		);
		$nor_result = array();
		if($type == 1){
			foreach($result['normalRepairRecords'] as $k => $v){
				$nor_result['normalRepairRecords'][$k]['content'] = $v['content'];
				$nor_result['normalRepairRecords'][$k]['material'] = $v['materal'];
				$nor_result['normalRepairRecords'][$k]['date'] = $v['date'];
				$nor_result['normalRepairRecords'][$k]['type'] = $v['type'];
				$nor_result['normalRepairRecords'][$k]['repairrecordsdate'] = $v['repairRecordsDate'];
			}
			unset($result['normalRepairRecords']);
			$result['normalRepairRecords'] = $nor_result['normalRepairRecords'];
			$insert_data['componentanalyzerepairtimes'] = count($result['componentAnalyzeRepairRecords']);
			$insert_data['outsideanalyzerepair']  = count($result['outsideAnalyzeRepairRecords']);
			$insert_data['lastmaintaintime']  =  $result['lastMainTainTime'];
			$insert_data['lastrepairtime']    =  $result['lastRepairTime'];
			$insert_data['maintaintimes']     =  $result['mainTainTimes'];
			$insert_data['mileageeveryyear']  =  $result['mileageEveryYear'];
			$insert_data['normalrepairrecords'] =  serialize($result);
			$insert_data['constructanalyzerepairrecords']  =  intval(count($result['constructAnalyzeRepairRecords']));
			$orther_data['transmissiontype'] = $result['transmissionType'];
			$orther_data['manufacturer'] = $result['manufacturer'];
			$orther_data['makedate'] = $result['makeDate'];
			$orther_data['cartype'] = $result['carType'];
			$orther_data['displacement'] = $result['displacement'];
			$orther_data['productionarea'] = $result['productionArea'];
			$orther_data['effluentstandard'] = $result['effluentStandard'];
		}else{
			foreach($result['normalRepairRecords'] as $k => $v){
				$nor_result['normalRepairRecords'][$k]['content'] = $v['content'];
				$nor_result['normalRepairRecords'][$k]['material'] = $v['material'];
				$nor_result['normalRepairRecords'][$k]['date'] = $v['date'];
				$nor_result['normalRepairRecords'][$k]['type'] = $v['type'];
				$nor_result['normalRepairRecords'][$k]['repairrecordsdate'] = $v['repairrecordsdate'];
			}
			unset($result['normalRepairRecords']);
			$result['normalRepairRecords'] = $nor_result['normalRepairRecords'];
			$insert_data['normalrepairrecords'] = serialize($result);
			$insert_data['lastmaintaintime']  =  $result['basic']['lastMainTainTime'];
			$insert_data['lastrepairtime']    =  $result['basic']['lastRepairTime'];
			$orther_data['displacement'] = $result['basic']['displacement'];
			$orther_data['manufacturer']  = $result['basic']['brand'].$result['basic']['model'];
			$orther_data['makedate']    =  $result['basic']['year'];
		}

		$repair = new CarRepairInfo();
		//检测是更新还是插入
		$is_set = $repair->getInfoByVin($vin);
		if($is_set){
			$state = $repair->updateInfo($is_set['rid'],$insert_data);
			$state = $is_set['rid'];
		}else{
			$state = $repair->inset_data($insert_data);
		}

		//返回数据格式
		if($state){
			$insert_data['rid'] = $return_info['rid'] =  $state;
			$return_info['normalrepairrecords'] = $result['normalRepairRecords'];
			unset($insert_data['normalrepairrecords']);
			$num = count($return_info['normalrepairrecords']);
			$return_info['introduction'] = $insert_data;
			$return_info['introduction'] = array_merge($insert_data,$orther_data);

			//把数据库ID写入缓存  避免重复查询
			$this->redis->hset($this->redis_report_key,$vin,$state);
			return $return_info;
		}
		return  false;
	}
}